package cn.ixiaoxin.deepchat.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.ixiaoxin.deepchat.VO.LoginVO;
import cn.ixiaoxin.deepchat.entity.User;
import cn.ixiaoxin.deepchat.mapper.UserMapper;
import cn.ixiaoxin.deepchat.service.UserService;
import cn.ixiaoxin.deepchat.util.Result;
import cn.ixiaoxin.deepchat.util.SecurityUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<?> register(User userDTO) {
        // 检查用户名是否存在
        User existingUser = userMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>()
                        .eq("username", userDTO.getUsername()));
        if (existingUser != null) {
            return Result.error("用户名已存在");
        }

        // 加密密码
        String encryptedPassword = SecurityUtil.encryptPassword(userDTO.getPassword());

        // 创建新用户
        User user = new User();
        user.setUsername(userDTO.getUsername());
        user.setPassword(encryptedPassword);
        user.setNickname(userDTO.getNickname());

        userMapper.insert(user);

        return Result.success("注册成功");
    }

    @Override
    public Result<?> login(User userDTO) {
        // 查找用户
        User user = userMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>()
                        .eq("username", userDTO.getUsername()));
        if (user == null) {
            return Result.error("用户名或密码错误");
        }

        // 验证密码
        if (!SecurityUtil.checkPassword(userDTO.getPassword(), user.getPassword())) {
            return Result.error("用户名或密码错误");
        }

        StpUtil.login(user.getId());
        String token = StpUtil.getTokenValue();
        LoginVO loginVO = new LoginVO();
        loginVO.setUser(user);
        loginVO.setToken(token);

        return Result.success(loginVO);
    }

    @Override
    public Result checkLogin() {
        if (StpUtil.isLogin()) {
            User user = userMapper.selectById(StpUtil.getLoginIdAsLong());
            if (user != null) {
                user.setPassword(null);
                LoginVO loginVO = new LoginVO();
                loginVO.setUser(user);
                loginVO.setToken(StpUtil.getTokenValue());
                return Result.success("已登录",loginVO);
            }
        }
        return Result.error("未登录");
    }

    @Override
    public Result<?> logout() {
        StpUtil.logout();
        return Result.success("退出成功");
    }
}
